package com.apes.framework.util.monitor.stackTrace;

import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.EventConst;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.Tools;
import com.apes.framework.util.monitor.AbstractMonitorService;
import com.apes.framework.util.monitor.Constants;
import org.springframework.stereotype.Service;

/**
 * 功能：跟踪线程栈信息(StackTrace)
 *
 * @author xul
 * @create 2020-06-19 15:05
 */

@Service
public class StackTraceService extends AbstractMonitorService<StackTrace> {
    private StackTraceRepository repository;

    public StackTraceService(StackTraceRepository repository, Cache cache) {
        super(cache, null);
        this.repository = repository;
    }

    @Listener(topic = EventConst.POST_PERSIST_EVENT + "," +
            EventConst.POST_UPDATE_EVENT + "," +
            EventConst.POST_REMOVE_EVENT + "," +
            EventConst.POST_LOAD_EVENT)
    public void onMessage(SimpleRequest request) {
        if (!isEnable()) {
            return;
        }
        String body = Tools.formatStackTrace();
        String id = MD5Util.encrypt(body);
        StackTrace stackTrace = new StackTrace();
        stackTrace.setId(id);
        stackTrace.setBody(body);
        stackTrace.setModel(request.getData().getClass().getName());
        add(stackTrace);
    }

    @Override
    public void run(StackTrace data) {
        StackTrace stackTrace = repository.findById(data.getId()).orElse(null);
        if (stackTrace == null) {
            stackTrace = new StackTrace();
            stackTrace.setId(data.getId());
            stackTrace.setModel(data.getModel());
            stackTrace.setBody(data.getBody());
        }
        stackTrace.incTimes();
        stackTrace.setEndedOn(DateUtil.format("yyyy-MM-dd'T'HH:mm:ss.SSS") + "+0800");
        repository.save(stackTrace);
    }

    @Override
    protected void deleteAllData() {
        repository.deleteAll();
    }

    @Override
    public String getTopic() {
        return Constants.CONST_STACK_TRACE_ENABLE;
    }
}
